import requests
import json
import configparser

# Load data from config.ini file
config = configparser.ConfigParser()
config.read('config.ini')

def crawlSongs(song_name):
    # BASE_URL = config['MUSICCRAWL']['BASE_URL']
    # type = ["search", "song", "lyric", "mv"]
    #
    # # 根据歌名获取歌曲ID
    # requst_url = BASE_URL + '?type=' + type[0] + '&s=' + s
    # data = requests.get(requst_url).text
    # dt = json.loads(data)
    #
    # if dt["result"]["songCount"] <= 0:
    #     crawlQQMusic(s)
    #
    # text = dt["result"]["songs"][0]
    # id = text["id"]
    # # 根据歌曲ID获取歌曲链接
    # url = BASE_URL + "?type=" + type[1] + "&id=" + str(id) + "&br=198000"
    # song = requests.get(url).text
    # song_url = (json.loads(song))["data"][0]["url"]

    SEARCH_BASE_URL = config['MUSICCRAWL']['SEARCH_BASE_URL_NETEASY']
    types = ["song", "songlist", "so", "url", "pic", "lrc"]
    cache = ["0", "1"]

    search_url = SEARCH_BASE_URL + '&id=' + song_name + '&type=' + types[2] + "&cache=" + cache[0] + "&nu=10"
    data = requests.get(search_url).text
    text = json.loads(data)
    if text["Code"] == "OK" and text["Body"] != None:
        song_id = text["Body"][0]["id"]
        title = text["Body"][0]["title"]
        author = text["Body"][0]["author"]
        song_url = text["Body"][0]["url"]
        song_url = requests.get(song_url).url
        pic_url = text["Body"][0]["pic"]
        lrc_url = text["Body"][0]["lrc"]
    else:
        song_url = crawlQQMusic(song_name)

    return song_url

def crawlQQMusic(song_name):
    SEARCH_BASE_URL = config['MUSICCRAWL']['SEARCH_BASE_URL_QQMUSIC'] # key---请求秘钥，默认值523077333
    types = ["song", "songlist", "so", "url", "pic", "lrc"] # 搜索类型从左到右依次为：单曲，歌单，搜索，链接，专辑图，歌词
    cache = ["0", "1"] # 默认=0不缓存，当cache=1时开启缓存，提高解析速度70%，数据不更新时，可把参数值改成cache=0访问一次即可清除缓存。
    size = ["m4a", "mp3", "hq", "ape", "flac"] # 音质，默认高清。参数值可为：m4a 压缩音质，mp3 高清，hq 高品质，ape 无损，flac 超级无损。

    search_url = SEARCH_BASE_URL + '&id=' + song_name + '&type=' + types[2] + "&cache=" + cache[0] + "&size=" + size[2] + "&nu=10" # nu----当type=so(搜索音乐)时有效，定义搜索结果数量，默认100
    data = requests.get(search_url).text
    text = json.loads(data)
    if text["Code"] == "OK" and text["songnum"] != 0 and text["Body"] != None:
        mid = text["Body"][0]["mid"]
        title = text["Body"][0]["title"]
        author = text["Body"][0]["author"]
        album = text["Body"][0]["album"]
        song_url = text["Body"][0]["url"]
        song_url = requests.get(song_url).url
        pic_url = text["Body"][0]["pic"]
        lrc_url = text["Body"][0]["lrc"]
    else:
        song_url = "songs not found..."

    return song_url

"""
if __name__ == '__main__':
    #print(crawlSongs('告白气球'))
    print(crawlQQMusic('勇气'))
"""